<template>
  <div>
    <n-card>
      <n-space>
        <n-button type="primary" style="margin-bottom: 5px;"
                  @click="ttsMakerShow = !ttsMakerShow">
          <template #icon>
            <n-icon>
              <AddCircleOutline/>
            </n-icon>
          </template>
          新增配音
        </n-button>
      </n-space>

      <n-data-table
          :columns="columns"
          :data="voiceList"
          :loading="tableLoading"
          :style="{ height: `${clientHeight - (layoutHeaderHeight  + tabsHeight + 130)}px` }"
          flex-height
      >
      </n-data-table>
      <n-space justify="end" style="margin-top: 10px">
        <n-pagination
            :display-order="['quick-jumper', 'pages', 'size-picker']"
            :item-count="tableTotal"
            :page-size="paginationReactive.pageSize"
            :page-sizes="paginationReactive.pageSizes"
            show-quick-jumper
            show-size-picker
            :on-update:page-size="onPageSizeChange"
            :on-update:page="onPageChange"
        />
      </n-space>
    </n-card>
    <n-drawer display-directive="show" v-model:show="ttsMakerShow" :width="drawerWidth">
      <n-drawer-content title="新增配音" closable>
        <TtsMaker model="long" :close-t-t-s-maker="closeTtsMaker"></TtsMaker>
      </n-drawer-content>
    </n-drawer>
    <!--音频播放器-->
    <n-modal
        v-model:show="audioShow"
        class="custom-card"
        preset="card"
        :style="bodyStyle"
        :title="audioOption.name"
        size="huge"
        :bordered="false"
    >
      <AudioPlayer
          :option="audioOption"
      />
    </n-modal>

    <n-modal
        v-model:show="audioTaskShow"
        class="custom-card"
        preset="card"
        :style="bodyStyle"
        title="任务详情"
        size="huge"
        style="width: 1000px;"
        :bordered="false"
        :segmented="segmented"
        @after-leave="getList"
    >
      <AudioTask :voiceId="selectVoice.id"></AudioTask>
    </n-modal>
  </div>

</template>

<script lang="ts" setup>
import {h, onMounted, onUnmounted, reactive, ref} from 'vue'
import {NButton, NPopselect, NTag, useNotification} from "naive-ui";
//@ts-ignore
import Bus from '@/components/file/box/GlobalUploader/utils/bus.js'
//@ts-ignore
import fileFunction from '@/libs/globalFunction/file.js'
import TtsMaker from "@/views/pages/audio/ttsMaker.vue";
import {AddCircleOutline} from "@vicons/ionicons5"

import AudioPlayer from '@/components/file/audio/AudioPlayer.vue'
import {storeToRefs} from "pinia";
import {useSystemStore} from "@/store/modules/useSystemStore";
import {voiceController} from "@/api/voice/ttsController.api";
import defaultMusicPng from '@/assets/images/file/file_music.png';
import AudioTask from "@/views/pages/audio/audioTask.vue";

const {
  clientHeight,
  layoutHeaderHeight,
  darkTheme,
  tabsHeight
} = storeToRefs(useSystemStore());


const audioShow = ref(false)
const voiceList = ref([])
const tableLoading = ref(false)
const formRef = ref(null)
const totalNum = ref(0)
const ttsMakerShow = ref(false)
const drawerWidth = ref(0)
const selectVoice = ref(null)
const closeTtsMaker = () => {
  ttsMakerShow.value = false
  getList()
}
const audioTaskShow = ref(false)

const audioOption = ref({
  src: '',
  title: '',
  coverImage: '',
})

const bodyStyle = {
  width: '600px'
}

const segmented = {
  content: 'soft',
  footer: 'soft'
}

const getList = () => {
  tableLoading.value = true
  voiceController.listVoice({
    page: paginationReactive.page,
    pageSize: paginationReactive.pageSize
  }).then((res) => {
    if (res.code === 200) {
      voiceList.value = res.data.list
      tableTotal.value = res.data.count
      const key = ref(0)
      voiceList.value?.forEach((item) => {
        item.key = key.value
        key.value = key.value + 1
      })
    }
  }).finally(() => {
    tableLoading.value = false
  })
}


const tableTotal = ref(0)

const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  pageSizes: [10, 30, 60]
})

const onPageChange = (page: number) => {
  paginationReactive.page = page
  getList()
}
const onPageSizeChange = (pageSize: number) => {
  paginationReactive.pageSize = pageSize
  getList()

}
onMounted(() => {
  getList()
  drawerWidth.value = window.innerWidth
  window.addEventListener('resize', () => {
    drawerWidth.value = window.innerWidth
  })
})

/**
 * 任务类型成功之后的回调
 * taskType: 任务类型
 * sId: 关联主键ID
 */
Bus.on('actionSuccess', () => {
  getList()
})


const columns = [
  {
    title: '序号',
    key: 'index',
    width: 60,
    align: 'center',
    render: (row, index) => {
      return index + 1
    }
  },
  {
    title: '语音名称',
    key: 'taskName',
    align: 'center',
    width: 200,
    ellipsis: {
      tooltip: true,
      lineClamp: 1
    }
  },
  {
    title: '类型',
    key: 'ttsType',
    align: 'center',
    width: 100,
    render: (row: any) => {
      let type = '付费'
      if (row.ttsType == 'free') {
        type = '免费'
      }
      return type
    }
  },
  {
    title: '状态',
    align: 'center',
    key: 'status',
    width: 100,
    render: (row) => {
      if (row.status == 'SUCCESS') {
        return h(NTag, {type: 'success'}, {default: () => '成功'})
      } else if (row.status == 'IN_PROGRESS') {
        return h(NTag, {type: 'warning'}, {default: () => '执行中'})
      } else if (row.status == 'SUBMITTED') {
        return h(NTag, {type: 'info'}, {default: () => '已提交'})
      } else if (row.status == 'FAILURE') {
        return h(NTag, {type: 'error'}, {default: () => '失败'})
      } else {
        return h(NTag, {type: 'warning'}, {default: () => '请等待'})
      }
    }
  }, {
    title: '声音设置',
    align: 'center',
    width: 200,
    render: (row) => {
      return row.voiceName + ' / ' + row.voiceRole + ' / ' + row.voiceStyle
    }
  }, {
    title: '总数/成功/失败',
    align: 'center',
    width: 200,
    render: (row) => {
      return row.totalNum + ' / ' + row.successNum + ' / ' + row.failNum
    }
  }, {
    title: '音量/音调/频率',
    width: 200,
    align: 'center',
    render: (row) => {
      return row.volume + ' / ' + row.pitch + ' / ' + row.rate
    }
  }, {
    title: '功能',
    key: 'operation',
    align: 'center',
    width: 300,
    render: (row: any) => {
      const buttons = [h(NButton, {
        type: 'error', onClick: () => {
          window.$dialog.error({
            title: "温馨提醒",
            content: "删除操作不可逆，是否继续？",
            positiveText: "确定",
            negativeText: "取消",
            onPositiveClick: () => {
              voiceController.voiceDelete(row.id).then((res) => {
                if (res.code === 200) {
                  window.$message.success('删除成功')
                  getList()
                }
              })
            }
          })
        }
      }, {default: () => '删除'})
        , h(NButton, {
          type: 'primary', style: 'margin-left:2px;', onClick: () => {
            audioTaskShow.value = true
            selectVoice.value = row
          }
        }, {default: () => '任务详情'})];
      if (row.userFileId) {
        buttons.push(
            h(NButton, {
              type: 'warning',style: 'margin-left:2px;', onClick: () => {
                const url = fileFunction.getViewFilePath(row);
                audioOption.value = {
                  src: url,
                  name: row.taskName,
                  coverImage: defaultMusicPng,
                }
                audioShow.value = true
              }
            }, {default: () => '播放'}))

      }
      return buttons
    }
  }
]


</script>
